<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" style="margin-bottom: 10px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span style="font-size:17px;font-weight: bold">我的订阅</span>
          </div>
          <div>

            <!--工具栏-->
            <div class="head-container">
              <div v-if="crud.props.searchToggle">
                <!--                  <label class="el-form-item-label">用户ID</label>-->
                <!--                  <el-input v-model="query.userId" clearable placeholder="用户ID" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />-->
                <label class="el-form-item-label">基金编码</label>
                <el-input v-model="query.codeNumber" clearable placeholder="基金编码" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
                <label class="el-form-item-label">基金名称</label>
                <el-input v-model="query.codeName" clearable placeholder="基金名称" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
                <rrOperation :crud="crud" />
              </div>
              <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
              <crudOperation :permission="permission" />

              <!--表单组件-->
              <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" title="基金订阅" width="500px">
                <el-form ref="form" :model="form" :rules="rules" size="middle" label-width="100px">
                  <el-form-item v-if="false" label="用户ID" prop="userId">
                    <el-input v-model="form.userId" />
                  </el-form-item>
                  <el-form-item label="选择基金" prop="codeNumber">
                    <v-selectpage
                      v-model="form.codeNumber"
                      style="width: 300px;"
                      :data="funds"
                      key-field="codeNumber"
                      show-field="codeName"
                      search-field="numberAndName"
                      :tb-columns="showFields"
                      title="基金"
                      placeholder="请选择基金"
                      class="form-control"
                      :page-size="10"
                      @values="singleValues"
                    />
                    <!--                      <v-selectpage v-model="form.codeNumber" :pagination="false" :data="funds" key-field="codeNumber" :tb-columns="showFields" title="基金" placeholder="请选择基金" class="form-control" @values="singleValues" />-->
                  </el-form-item>
                  <!--                  <el-form-item v-if="false" label="基金编码" prop="codeNumber">-->
                  <!--                    <el-input v-model="form.codeNumber" style="width: 300px;" :disabled="true" />-->
                  <!--                  </el-form-item>-->
                  <el-form-item v-if="false" label="基金名称" prop="codeName">
                    <el-input v-model="form.codeName" style="width: 300px;" :disabled="true" />
                  </el-form-item>
                  <el-form-item label="涨幅提醒值" prop="increaseReminder">
                    <el-input-number v-model.number="form.increaseReminder" onkeyup="value=value.replace(/[^\d]/g,'')" :min="-10" :max="10" style="width: 160px;" />
                  </el-form-item>
                  <el-form-item label="跌幅提醒值" prop="fallReminder">
                    <el-input-number v-model.number="form.fallReminder" :min="-10" :max="10" style="width: 160px;" @input.native="inputhandle" />
                  </el-form-item>
                  <!--                    <el-form-item label="通知时间">-->
                  <!--                      <el-input v-model="form.remindTime" style="width: 370px;" />-->
                  <!--                    </el-form-item>-->
                </el-form>

                <div slot="footer" class="dialog-footer">
                  <el-button type="text" @click="crud.cancelCU">取消</el-button>
                  <!--                                        <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>-->
                  <el-button v-if="crud.status.add === 1" :loading="crud.cu === 2" type="primary" @click="createSubscribe">确认</el-button>
                  <el-button v-else :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
                </div>

              </el-dialog>

              <!--表格渲染-->
              <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="middle" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
                <el-table-column type="selection" width="55" />
                <el-table-column type="index" label="序号" width="55" />
                <!--                  <el-table-column prop="id" label="主键ID" />-->
                <!--                  <el-table-column prop="userId" label="用户ID" />-->
                <el-table-column prop="codeNumber" label="基金编码">
                  <template slot-scope="scope">
                    <el-tooltip :content="`${scope.row.codeName} 基金详情`" placement="top">
                      <router-link :to="`/detail/${scope.row.codeNumber}`">
                        <span style="color: #2b87f3;text-decoration: underline;cursor: pointer;">{{ scope.row.codeNumber }}</span>
                      </router-link>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="codeName" label="基金名称" />
                <el-table-column prop="increaseReminder" label="涨幅提醒值">
                  <template v-slot:="scope">
                    <span style="color: #F56C6C">{{ scope.row.increaseReminder }}%</span>
                  </template>
                </el-table-column>
                <el-table-column prop="fallReminder" label="跌幅提醒值">
                  <template v-slot:="scope">
                    <span style="color: #67C23A;">{{ scope.row.fallReminder }}%</span>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" :formatter="dateFormat" />
                <el-table-column prop="updateTime" label="更新时间" :formatter="dateFormat" />
                <!--                  <el-table-column prop="deleted" label="逻辑删除" />-->
                <!--                  <el-table-column prop="remindTime" label="通知时间" />-->
                <el-table-column v-permission="['admin','userSubscribe:edit','userSubscribe:del']" label="操作" width="150px" align="center">
                  <template slot-scope="scope">
                    <udOperation
                      :data="scope.row"
                      :permission="permission"
                    />
                  </template>
                </el-table-column>
              </el-table>
              <!--分页组件-->
              <pagination />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudUserSubscribe from '@/api/front/userSubscribe/userSubscribe'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'

// 日期格式化
import moment from 'moment'

import { mapGetters } from 'vuex'

const defaultForm = { id: null, userId: null, codeNumber: null, codeName: null, increaseReminder: 3, fallReminder: -3, createTime: null, updateTime: null, deleted: null, remindTime: null }
export default {
  name: 'UserSubscribe',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: 'UserSubscibeService', url: 'api/front/userSubscribe', idField: 'id', sort: 'id,desc', querySelf: true, crudMethod: { ...crudUserSubscribe }})
  },
  data() {
    return {
      permission: {
        add: ['admin', 'userSubscribe:add'],
        edit: ['admin', 'userSubscribe:edit'],
        del: ['admin', 'userSubscribe:del']
      },
      rules: {
        codeNumber: [
          { required: true, message: '基金编码不能为空', trigger: 'blur' }
        ],
        codeName: [
          { required: true, message: '基金名称不能为空', trigger: 'blur' }
        ],
        increaseReminder: [
          { required: true, message: '涨幅提醒值（默认值3）不能为空', trigger: 'blur' }
        ],
        fallReminder: [
          { required: true, message: '跌幅提醒之（默认值-3）不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        // { key: 'userId', display_name: '用户ID' },
        { key: 'codeNumber', display_name: '基金编码' },
        { key: 'codeName', display_name: '基金名称' }
      ],

      // 自定义选择项
      showFields: [
        { title: '基金代码', data: 'codeNumber' },
        { title: '基金名称', data: 'codeName' },
        { title: '基金类型', data: 'codeType' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'funds',
      'user'
    ])
  },
  mounted() {
    console.log(this.funds)
    if (this.funds.length === 0) {
      this.$store.dispatch('QueryFund')
      console.log(this.funds)
    }
  },
  methods: {
    inputhandle({ target }) {
      target.value = target.value.replace(/\[^0-9\]/gi, '')
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      // 只查询自己的数据
      this.query.userId = this.user.id
      return true
    },

    // 选择器返回事件
    singleValues(data) {
      console.log(data)
      this.form.codeName = data[0].codeName
      this.form.userId = this.user.id
    },

    // 时间格式化
    dateFormat(row, column) {
      var date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },

    // 新增订阅
    createSubscribe() {
      this.$refs.form.validate(v => {
        if (!v) {
          return
        } else {
          this.crud.status.add = CRUD.STATUS.PROCESSING
          crudUserSubscribe.add(this.form).then(res => {
            this.crud.status.add = CRUD.STATUS.NORMAL
            this.crud.resetForm()
            switch (res) {
              case -1:
                this.$message.error('基金订阅失败，请稍后重试！')
                break
              case 0:
                this.$message.info('基金订阅数量达到上限！')
                break
              case 1:
                this.$message.success('基金订阅成功！')
                break
            }
            this.crud.toQuery()
          })
        }
      })
    },

    resultFormat(resp) {
      if (resp && resp.data) return resp.data.values.gridResult
    },

    // 自定义下拉列表行显示
    renderRow(row) {
      let result = ''
      if (row && Object.keys(row).length) {
        result = `<b>${row.codeNumber}</b> ${row.codeName}`
        return result
      }
    }

  }

}
</script>

<style lang="scss" scoped>
.subscribe-container{
  height: 100%;

  //border-top: 1px solid #dcdfe6;
  //padding: 10px;

  .app-container{
    height: 100%;
    //padding-bottom: 20px;
    //background: rgb(199,237,204)
  }

  .el-row,.el-col,.el-card{
  }
}

</style>
